﻿namespace Org.Loon.Framework.Xna.Game.Core.Graphics.OpenGL.Particle
{

    using System.Collections.Generic;
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Graphics;
    using System;

    public class ParticleManager
    {
   
        private Game game;

        private List<Type> particleSystemTypes;

        public ParticleManager(Game game)
        {
            particleSystemTypes = new List<Type>();
            this.game = game;
        }

        public void Register(ParticleSystem psystem)
        {
            particleSystemTypes.Add(psystem.GetType());
            game.Components.Add(psystem);
        }

        public void Remove(Type particleSystemType)
        {
            particleSystemTypes.Remove(particleSystemType);
            Object particleSystem = game.Services.GetService(particleSystemType);
            game.Components.Remove((IGameComponent)particleSystem);

        }

        private int FindParticleIndexFromType(Type type)
        {
            int index = 0;
            for (int i = 0; i < game.Components.Count; i++)
                if (game.Components[i].GetType() == type)
                {
                    index = i;
                    break;
                }
            return index;
        }

        public List<ParticleSystem> GetCollidableParticleSystems()
        {
            List<ParticleSystem> result = new List<ParticleSystem>();

            for (int i = 0; i < this.particleSystemTypes.Count; i++)
            {
                int _index = this.FindParticleIndexFromType(particleSystemTypes[i]);
                ParticleSystem sys = (ParticleSystem)game.Components[_index];
                if (sys.isCollidable)
                {
                    result.Add(sys);
                }
            }

            return result;
        }

        public void AddParticleSystem(Type type, Vector2 where)
        {
            int index = FindParticleIndexFromType(type);
            ((ParticleSystem)game.Components[index]).AddParticles(where);
        }

        public virtual void Update(GameTime gameTime)
        {

        }

        public virtual void Draw(SpriteBatch spriteBatch, GameTime gameTime)
        {
   
        }
    }
}
